/*!
 * Koa CMS Backstage management
 *
 * Copyright JS suwenhao
 * Released under the ISC license
 * Email swh1057607246@qq.com
 *
 */
const user = require("./user"); // 用户接口
const channels = require('./channels')
const articles = require('./articles')
const article = require('./article')
const comments = require('./comments')
const comment = require('./comment')
const authorizations = require('./authorizations')
const search = require('./search')
const suggestion = require('./suggestion')
const sms = require('./sms')
const address = require('../../../address')

const multer = require("koa-multer");
//配置
let storage = multer.diskStorage({
  //文件保存路径
  destination: function (req, file, cb) {
    cb(null, "public/uploads/"); //注意路径必须存在
  },
  //修改文件名称
  filename: function (req, file, cb) {
    let fileFormat = file.originalname.split(".");
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  },
});
//加载配置
let upload = multer({ storage });
const router = require('koa-router')()

 // 多级匹配 用户模块
router.use('/user', user)

router.use('/channels', channels)

router.use('/articles', articles)

router.use('/article', article)

router.use('/comments', comments)

router.use('/comment', comment)

router.use('/authorizations', authorizations)

router.use('/search', search)

router.use('/suggestion', suggestion)

router.use('/sms', sms)

router.get('/announcements', async ctx => {
  return  {
      data : {
        total_count: 3,
        page: 1, 
        per_page: 10,
        results : [{
            id: 1,
            title: '黑马程序员招新啦, 诚招各路编程高手',
            pubdate: '2021/05/25 16:52:39'
        },{
            id: 2,
            title: '传智教育成为A股中第一支成功IPO的教育产业股',
            pubdate: '2021/1/25 16:52:39'
        },{
            id: 3,
            title: 'web前端工程师训练营来袭, 小伙伴们踊跃报名',
            pubdate: '2021/02/25 08:52:39'
        }]
      }
  }
})
// 上传头像
router.post(
  "/upload",
  upload.fields([{ name: "image", maxCount: 1 }]),
  async (ctx) => {
    const { image } = ctx.req.files;
    let filePath = "";
    if (image && image.length) {
      filePath = `http://${address.host}:${address.port}/uploads/` + image[0].filename;
    }
    ctx.status = 200
    return { data: { url: filePath } };
  }
);
module.exports = router.routes();
